﻿#ifndef WRWORKTCPCOMMSERVERWORKDEALER
#define WRWORKTCPCOMMSERVERWORKDEALER

#include "WRWorkTcpCommServerInterface.h"
#include "WRWorkTcpCommServerInterfaceActivator.h"
#include "../WRWorkTcpComm.h"
#include "../WRWorkTcpCommConsts.h"
#include "../WRWorkDealer.h"
#include "../../WRSoft-Utility/Runtime/WRDataPacket.h"
#include <QMutex>
#include <QRunnable>
#include <QThreadPool>

/********************
class Parser
{
public:
    bool parse(const unsigned char* buf, int len, T& val);
};
********************/

//表示工作TCP通讯服务器业务处理接口。
template <class T, class TParser>
class WRWorkTcpCommServerWorkDealer : public WRWorkTcpCommServerInterface
{
private:
    WRWorkDealer* m_dealer;
    TParser m_parser;
    QMutex* m_mutex;

    //处理项目。
    class ProcEntry : public QRunnable
    {
    private:
        T m_args;
        WRWorkTcpCommServerWorkDealer* m_owner;
        int m_serial;

    public:
        //初始化处理项目。
        inline ProcEntry(const T& args, WRWorkTcpCommServerWorkDealer* owner, int serial)
            : m_args(args), m_owner(owner), m_serial(serial)
        {
            if (m_owner->affair())
            {
                m_owner->affair()->addRef();
            }
            else
            {
                m_owner->object()->addRef();
            }
        }
        //清理当前对象所占用的相关资源。
        ~ProcEntry(void)
        {
            if (m_owner->affair())
            {
                m_owner->affair()->release();
            }
            else
            {
                m_owner->object()->release();
            }
        }

        //获取参数对象。
        inline T& args(void)
        {
            return m_args;
        }
        //获取参数对象。
        inline const T& args(void) const
        {
            return m_args;
        }

        //获取所有者。
        inline WRWorkTcpCommServerWorkDealer* owner(void) const
        {
            return m_owner;
        }
        //获取序列号。
        inline int serial(void) const
        {
            return m_serial;
        }

        //运行处理。
        void run()
        {
            int id = 0;
            int index = -1;
            WRWorkAffair* affair = 0;
            int result = m_owner->m_dealer->create(&m_args, &affair);
            if (result == WRErrors::None)
            {
                WRWorkTcpCommServerAffair* affair2 = m_owner->object()->createAffair(affair);
                id = affair2->id();
                index = affair2->index();
            }

            WRDataPacket* packet;
            if (m_owner->affair())
            {
                char* p;
                packet = WRDataPacket::allocate<48>();
                packet->buffer(&p);

                WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
                WRBytes::write((WR32s)(48), p + 4);//帧长度
                WRBytes::write((WR16u)(m_owner->object()->index()), p + 8);//工作对象索引
                WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
                WRBytes::write((WR32s)(m_owner->affair()->id()), p + 12);
                WRBytes::write((WR16u)(m_owner->affair()->index()), p + 16);//工作对象索引
                WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIITreat, p + 18);//类型（接口处理）
                WRBytes::write((WR16u)(m_owner->index()), p + 20);//接口索引
                WRBytes::write((WR32s)(m_serial), p + 24);//指令序号
                WRBytes::write((WR32s)(result), p + 28);//结果状态
                WRBytes::write((WR32s)(index), p + 32);//工作事务索引
                WRBytes::write((WR32s)(id), p + 36);//工作事务标识
                WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 40);//版本
                WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 44);//帧尾
            }
            else
            {
                char* p;
                packet = WRDataPacket::allocate<40>();
                packet->buffer(&p);

                WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
                WRBytes::write((WR32s)(40), p + 4);//帧长度
                WRBytes::write((WR16u)(m_owner->object()->index()), p + 8);//工作对象索引
                WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectIITreat, p + 10);//类型（接口处理）
                WRBytes::write((WR16u)(m_owner->index()), p + 12);//接口索引
                WRBytes::write((WR32s)(m_serial), p + 16);//指令序号
                WRBytes::write((WR32s)(result), p + 20);//结果状态
                WRBytes::write((WR32s)(index), p + 24);//工作事务索引
                WRBytes::write((WR32s)(id), p + 28);//工作事务标识
                WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 32);//版本
                WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 36);//帧尾
            }
            if (!m_owner->sendData(packet))
            {
                packet->release();
            }
        }
    };

public:
    //初始化工作TCP通讯服务器业务处理接口。
    WRWorkTcpCommServerWorkDealer(const QUuid& uuid, const QString& name, int index, WRWorkTcpCommServerObject* target, WRWorkDealer* dealer)
        : WRWorkTcpCommServerInterface(uuid, name, index, target), m_dealer(dealer)
    {
        //add code here
    }
    //初始化工作TCP通讯服务器业务处理接口。
    WRWorkTcpCommServerWorkDealer(const QUuid& uuid, const QString& name, int index, WRWorkTcpCommServerAffair* target, WRWorkDealer* dealer)
        : WRWorkTcpCommServerInterface(uuid, name, index, target), m_dealer(dealer)
    {
        //add code here
    }

    //清理当前对象所占用的相关资源。
    ~WRWorkTcpCommServerWorkDealer(void)
    {
        //add code here
    }

    //处理数据。
    void procData(const unsigned char* buf, int len)
    {
        buf += 2;
        len -= 2;
        WR32s serial = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;
        WR32s argsLen = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;

        T args;
        if (argsLen <= len && m_parser.parse(buf, argsLen, args))
        {
            ProcEntry* procEntry = new ProcEntry(args, this, serial);
            QThreadPool::globalInstance()->start(procEntry);
        }
        else
        {
            //add code here on parsing failed!
        }
    }
};

//表示工作TCP通讯服务器业务处理激活器。
template <class T, class TParser, class TUuidValue, class TNameValue>
class WRWorkTcpCommServerWorkDealerActivator : public WRWorkTcpCommServerInterfaceActivator
{
public:
    //初始化工作TCP通讯服务器业务处理激活器。
    WRWorkTcpCommServerWorkDealerActivator(void)
    {
        TUuidValue uuid;
        WRWorkTcpComm::enrollServerInterface(uuid(), this);
    }
    //释放当前对象所占用的相关资源。
    ~WRWorkTcpCommServerWorkDealerActivator(void)
    {
        TUuidValue uuid;
        WRWorkTcpComm::cancelServerInterface(uuid());
    }

    //创建接口实例。
    WRWorkTcpCommServerInterface* create(int index, WRWorkTcpCommServerObject* target, void* reference)
    {
        TUuidValue uuid;
        TNameValue name;
        return new WRWorkTcpCommServerWorkDealer<T, TParser>(uuid(), name(), index, target, (WRWorkDealer*)reference);
    }
    //创建接口实例。
    WRWorkTcpCommServerInterface* create(int index, WRWorkTcpCommServerAffair* target, void* reference)
    {
        TUuidValue uuid;
        TNameValue name;
        return new WRWorkTcpCommServerWorkDealer<T, TParser>(uuid(), name(), index, target, (WRWorkDealer*)reference);
    }
};

#endif // WRWORKTCPCOMMSERVERWORKDEALER
